#pragma once

#include "Socket.hpp"
#include <poll.h>

using namespace socket_ns;
using namespace log_ns;

class PollServer
{
private:
    const static int g_num = sizeof(fd_set) * 8;
    const static int g_defaultfd = -1;

public:
    PollServer(in_port_t port)
        : _port(port), _listenSocket(std::make_unique<TcpSocket>())
    {
        _listenSocket->BuildListenSocket(_port);
    }

    void InitServer()
    {
        // 初始化 fd 数组
        for (int i = 0; i < g_num; ++i)
        {
            fd_events[i].fd = g_defaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }

        // 默认直接添加 _listen_sockfd 到数组中
        fd_events[0].fd = _listenSocket->GetSockfd();
        fd_events[0].events = POLLIN;
    }

    // 处理新连接就绪
    void Accepter()
    {
        InetAddr peer;
        int sockfd = _listenSocket->Accepter(&peer); // 一定不会被阻塞
        if (sockfd >= 0)
        {
            LOG(INFO, "Get a new link, client info: [%s], sockfd: %d\n", peer.GetAddrStr().c_str(), sockfd);
            // 将 fd 添加进辅助数组内，该函数结束之后，即可对 select 参数重置
            bool flag = false;
            for (int i = 1; i < g_num; ++i)
            {
                if (fd_events[i].fd == g_defaultfd)
                {
                    flag = true;
                    fd_events[i].fd = sockfd;
                    fd_events[i].events = POLLIN;
                    LOG(INFO, "Add %d to fd_events success!\n", sockfd);
                    break;
                }
            }
            if (!flag)
            {
                // 数组已满
                LOG(WARNING, "Server Is Full!\n");
                ::close(sockfd);
                // 扩容
            }
        }
        else
        {
            return;
        }
    }

    // 处理普通 fd 就绪
    void HandlerIO(int i)
    {
        char buffer[1024];
        ssize_t n = ::recv(fd_events[i].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "Client says# \n"
                      << buffer << std::endl;
            std::string content = "<html><body><h1>Hello World</h1></body></html>";
            std::string echo_str = "HTTP/1.0 200 OK\r\n";
            echo_str += "Content-Type: text/html\r\n";
            echo_str += ("Content-Length: " + std::to_string(content.size()) + "\r\n\r\n");
            echo_str += content;
            // echo_str += buffer;
            ::send(fd_events[i].fd, echo_str.c_str(), echo_str.size(), 0);
        }
        else if (n == 0)
        {
            LOG(INFO, "Client quit...\n");
            ::close(fd_events[i].fd);
            fd_events[i].fd = g_defaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }
        else
        {
            LOG(ERROR, "Recv Error, %d -> %s\n", errno, strerror(errno));
            ::close(fd_events[i].fd);
            fd_events[i].fd = g_defaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }
    }

    void HandlerEvent()
    {
        // 事件派发 
        for (int i = 0; i < g_num; ++i)
        {
            if (fd_events[i].fd == g_defaultfd)
                continue;
            // 到这里就是合法 fd，但不一定就绪，得找出就绪的
            if (fd_events[i].revents & POLLIN)
            {
                if (fd_events[i].fd == _listenSocket->GetSockfd())
                {
                    Accepter();
                }
                else
                {
                    // 普通 IO fd 处理
                    HandlerIO(i);
                }
            }
        }
    }

    void Loop()
    {
        int timeout = -1; // ms
        while (true)
        {
            int n = ::poll(fd_events, g_num, timeout);
            switch (n)
            {
            case 0:
                LOG(DEBUG, "Time Out!\n");
                break;
            case -1:
                LOG(ERROR, "Poll Error, errno: %d -> %s\n", errno, strerror(errno));
                break;
            default:
                LOG(INFO, "Haved event ready, n: %d\n", n);
                // 如果数据就绪但一直不处理，select 会一直通知进程，直至进程处理
                HandlerEvent();
                PrintDebug();
                // sleep(3);
                break;
            }
        }
    }

    void PrintDebug()
    {
        std::cout << "fd list: ";
        for (int i = 0; i < g_num; ++i)
        {
            if (fd_events[i].fd == g_defaultfd)
                continue;
            std::cout << fd_events[i].fd << " ";
        }
        std::cout << std::endl;
    }

    ~PollServer()
    {
    }

private:
    in_port_t _port; // 服务器怎么能没有端口号
    std::unique_ptr<Socket> _listenSocket;

    // 辅助数组，来保存所有合法 fd 
    struct pollfd fd_events[g_num];
};